<template>
  <div class="box">
    <el-form
      ref="userForm"
      :model="forms"
      :rules="userRules"
      :label-position="labelPosition"
      label-width="100px"
    >
      <el-form-item prop label="排序">
        <el-input class="form_input" v-model="forms.sort"></el-input>
      </el-form-item>
      <el-form-item prop="name" label="名称">
        <el-input class="form_input" v-model="forms.name" placeholder="请输入名称"></el-input>
      </el-form-item>
      <el-form-item prop="express_id" label="快递公司">
        <el-select v-model="forms.express_id" filterable placeholder="请选择">
          <el-option v-for="item in expresslist" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop label="计费方式">
        <el-radio-group v-model="forms.carry_mode_type">
          <el-radio :label="0">按件计费</el-radio>
          <el-radio :label="1">按重量计费</el-radio>
        </el-radio-group>
        <div class="carryMode_box">
          <el-table :data="carryMode" v-if="forms.carry_mode_type == 0">
            <el-table-column label="配送范围" prop="district">
              <template slot-scope="scope">
                <span>{{ scope.row.district_value }}</span>
                <div v-if="scope.$index > 0">
                  <el-button type="text" @click="EditHandle(scope.row.district, scope.$index)">编辑</el-button>
                  <el-button type="text" @click="DelHandle(scope.$index)">删除</el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="首件(个)">
              <template slot-scope="scope">
                <el-input-number :controls="false" v-model="scope.row.first_piece"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="运费(元)">
              <template slot-scope="scope">
                <el-input-number :controls="false" v-model="scope.row.first_amount"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="续件(个)">
              <template slot-scope="scope">
                <el-input-number :controls="false" v-model="scope.row.second_piece"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="运费(元)">
              <template slot-scope="scope">
                <el-input-number :controls="false" v-model="scope.row.second_amount"></el-input-number>
              </template>
            </el-table-column>
          </el-table>
          <el-table :data="carryMode" v-if="forms.carry_mode_type == 1">
            <el-table-column label="配送范围" prop="district">
              <template slot-scope="scope">
                <span>{{ scope.row.district_value }}</span>
                <div v-if="scope.$index > 0">
                  <el-button type="text" @click="EditHandle(scope.row.district, scope.$index)">编辑</el-button>
                  <el-button type="text" @click="DelHandle(scope.$index)">删除</el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="首重(克)">
              <template slot-scope="scope">
                <el-input-number :controls="false" v-model="scope.row.first_weight"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="运费(元)">
              <template slot-scope="scope">
                <el-input-number :controls="false" v-model="scope.row.first_amount"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="续重(克)">
              <template slot-scope="scope">
                <el-input-number :controls="false" v-model="scope.row.second_weight"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="运费(元)">
              <template slot-scope="scope">
                <el-input-number :controls="false" v-model="scope.row.second_amount"></el-input-number>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="text" @click="AddHandle(1)">+添加配送区域</el-button>
        </div>
      </el-form-item>
      <el-form-item label="不配送区域">
        <el-button type="text" v-if="no_carry.length == 0" @click="AddHandle(2)">+添加不配送区域</el-button>
        <el-button type="text" v-else @click="EditHandle(no_carry, -1)">编辑</el-button>
        {{ no_carry_value }}
      </el-form-item>
      <el-form-item prop label="是否默认">
        <el-radio-group v-model="forms.is_default">
          <el-radio :label="0">否</el-radio>
          <el-radio :label="1">是</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button @click="addSave" v-if="type == 'add'">确定</el-button>
        <el-button @click="editSave" v-else>确定</el-button>
      </el-form-item>
    </el-form>

    <el-dialog :destroy-on-close="true" append-to-body :visible.sync="drawer" width="800px">
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="panel-header">
            <span>地区选择</span>
            <el-input size="medium" placeholder="搜索省/市/区" v-model="address_keyword"></el-input>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="panel-header">
            <span>已选择</span>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="panel-body">
            <el-tree
              :props="defaultProps"
              ref="tree"
              node-key="value"
              :data="regionData"
              show-checkbox
              @check="handleCheckChange"
            ></el-tree>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="panel-body">
            <el-tree
              ref="tree2"
              node-key="value"
              v-show="select_data.length > 0"
              :data="select_data"
            >
              <span class="custom-tree-node" slot-scope="{node, data}">
                <span>{{ node.label }}</span>
                <span>
                  <el-button type="text" size="mini" @click="() => remove(node, data)">取消</el-button>
                </span>
              </span>
            </el-tree>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <div class="panel-foot">
          <div>
            <el-button v-if="select_data.length < 34" @click="checkedAll">全选</el-button>
            <el-button v-else @click="checkedAll">取消全选</el-button>
          </div>
          <div>
            <el-button @click="hidedailog">取消</el-button>
            <el-button type="primary" @click="confirm">确定</el-button>
          </div>
        </div>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import {
  savefreight,
  getexpress,
  editfreight,
  getfreightdetail
} from "@/api/shop/freight";
import { objextend } from "@/utils/index";
import { regionData, CodeToText, TextToCode } from "element-china-area-data";
export default {
  name: "Editfreight",
  data() {
    const _this = this;
    return {
      labelPosition: "left",
      forms: {
        name: "",
        express_id: "",
        carry_mode_type: 0,
        is_default: 0,
        sort: 1,
        status: 1
      },
      u_type: 1,
      address_keyword: "",
      regionData: regionData,
      drawer: false,
      carryMode: [
        {
          district: "",
          first_piece: "",
          first_weight: "",
          first_amount: "",
          second_piece: "",
          second_weight: "",
          second_amount: "",
          district_value: "全国统一运费"
        }
      ],
      no_carry_value: "",
      no_carry: [],
      list: [],
      defaultProps: {
        disabled: function(data, note) {
          if (_this.list.indexOf(data.value) > -1) {
            return true;
          } else {
            return false;
          }
        }
      },
      halfCheckedKeys: [],
      select_data: [],
      select_data_y: [],
      select_data_s: [],
      checkedKeys: [],
      expresslist: [],
      userRules: {
        name: [
          {
            required: true,
            trigger: "blur",
            message: "请输入模板名称"
          }
        ],
        express_id: [
          {
            required: true,
            trigger: "change",
            message: "请选择快递"
          }
        ]
      }
    };
  },
  props: {
    type: {
      type: String,
      default: "add"
    },
    id: {
      type: Number,
      default: -2
    }
  },
  watch: {
    id() {
      console.log("as");
      this.forms = {
        name: "",
        express_id: "",
        carry_mode_type: 0,
        is_default: 0,
        sort: 1,
        status: 1
      };

      this.getlist();
      this.getexpress();
    }
  },

  methods: {
    getexpress() {
      let data = {};
      getexpress(data).then(res => {
        this.expresslist = res.msg;
      });
    },
    //
    remove(node, data) {
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex(d => d.value === data.value);
      const i = this.checkedKeys.findIndex(d => d === data.value);
      children.splice(index, 1);
      this.checkedKeys.splice(i, 1);
      const grparent = parent.parent;
      if (
        grparent &&
        grparent.data.value &&
        this.halfCheckedKeys.indexOf(grparent.data.value) == -1
      ) {
        this.halfCheckedKeys.push(grparent.data.value);
      }
      if (this.halfCheckedKeys.indexOf(parent.data.value) == -1) {
        this.halfCheckedKeys.push(parent.data.value);
      }
      this.$refs.tree.setChecked(data.value, false, true);
    },
    //全选/取消 地址
    checkedAll() {
      if (this.select_data.length < 34) {
        this.$refs.tree.setCheckedNodes(this.regionData);
        let checkedKeys = this.$refs.tree.getCheckedKeys();
        this.checkedKeys = checkedKeys;
        this.getselect(checkedKeys);
        // this.select_data = JSON.parse(JSON.stringify(this.regionData));
      } else {
        this.$refs.tree.setCheckedNodes([]);
        this.select_data = [];
      }
    },
    //选择地址
    handleCheckChange(a, b) {
      let checkedKeys = b.halfCheckedKeys.concat(b.checkedKeys);
      this.halfCheckedKeys = b.halfCheckedKeys;
      this.checkedKeys = b.checkedKeys;
      this.getselect(checkedKeys);
    },
    //获取选择地址
    getselect(checkedKeys) {
      let regionData = JSON.parse(JSON.stringify(this.regionData));
      let province = regionData.filter(a => {
        return checkedKeys.indexOf(a.value) > -1;
      });
      province.forEach(c => {
        let citys = c.children.filter(a => {
          return checkedKeys.indexOf(a.value) > -1;
        });
        c.children = citys;
        c.children.forEach(e => {
          if (e.children) {
            let areas = e.children.filter(a => {
              return checkedKeys.indexOf(a.value) > -1;
            });
            e.children = areas;
          }
        });
      });
      this.select_data = province;
    },
    showdailog() {
      let list = [];
      let index = this.index;
      this.carryMode.forEach((a, i) => {
        if (i != index) {
          list = list.concat(a.district);
        }
      });
      this.list = list;
      this.drawer = true;
    },
    hidedailog() {
      this.drawer = false;
    },
    AddHandle(type) {
      this.index = 0;
      this.u_type = type;
      if (type == 1) {
        this.select_data = this.select_data_y;
      } else {
        this.select_data = this.select_data_s;
      }
      this.showdailog();
    },
    //确认
    confirm() {
      // console.log(this.select_data)
      if (this.u_type == 1) {
        this.select_data_y = this.select_data;
        this.select_data = [];
        this.addcarryMode();
      } else {
        this.select_data_s = this.select_data;
        this.select_data = [];
        this.addnocarry();
      }
    },
    //新增不可配送区域
    addnocarry() {
      let a = "";
      this.select_data_s.forEach((b, i) => {
        let h = i < this.select_data_s.length - 1;
        let j = this.checkedKeys.indexOf(b.value);
        if (j > -1) {
          this.checkedKeys.splice(j, 1);
        }
        if (this.halfCheckedKeys.indexOf(b.value) > -1) {
          a = a + b.label + "【";
          b.children.forEach((c, i) => {
            let h = i < b.children.length - 1;
            let j = this.checkedKeys.indexOf(c.value);
            if (j > -1) {
              this.checkedKeys.splice(j, 1);
            }
            if (this.halfCheckedKeys.indexOf(c.value) > -1) {
              a = a + c.label + "(";
              c.children.forEach((d, i) => {
                let h = i < c.children.length - 1;
                a = a + d.label + (h ? "," : "");
              });
              a = a + (h ? ")," : ")");
            } else {
              a = a + c.label + (h ? "," : "");
            }
          });
          a = a + (h ? "】," : "】");
        } else {
          a = a + b.label + (h ? "," : "");
        }
      });
      let checkedKeys = JSON.parse(JSON.stringify(this.checkedKeys));
      // this.list.concat(checkedKeys)
      this.no_carry_value = a;
      this.no_carry = checkedKeys;
      this.drawer = false;
    },
    //新增模板地区
    addcarryMode() {
      let a = "";
      this.select_data_y.forEach((b, i) => {
        let h = i < this.select_data_y.length - 1;
        let j = this.checkedKeys.indexOf(b.value);
        if (j > -1) {
          this.checkedKeys.splice(j, 1);
        }
        if (this.halfCheckedKeys.indexOf(b.value) > -1) {
          a = a + b.label + "【";
          b.children.forEach((c, i) => {
            let h = i < b.children.length - 1;
            let j = this.checkedKeys.indexOf(c.value);
            if (j > -1) {
              this.checkedKeys.splice(j, 1);
            }
            if (this.halfCheckedKeys.indexOf(c.value) > -1) {
              a = a + c.label + "(";
              c.children.forEach((d, i) => {
                let h = i < c.children.length - 1;
                a = a + d.label + (h ? "," : "");
              });
              a = a + (h ? ")," : ")");
            } else {
              a = a + c.label + (h ? "," : "");
            }
          });
          a = a + (h ? "】," : "】");
        } else {
          a = a + b.label + (h ? "," : "");
        }
      });
      let checkedKeys = JSON.parse(JSON.stringify(this.checkedKeys));
      // this.list.concat(checkedKeys)
      this.select_data = [];
      if (this.index > 0) {
        this.carryMode[this.index].district_value = a;
        this.carryMode[this.index].district = checkedKeys;
      } else {
        this.carryMode.push({
          district_value: a,
          first_piece: "",
          first_weight: "",
          first_amount: "",
          second_piece: "",
          second_weight: "",
          second_amount: "",
          district: checkedKeys
        });
      }

      this.drawer = false;
    },
    EditHandle(list, index) {
      this.index = index;
      if (index == -1) {
        this.u_type = 2;
      } else {
        this.u_type = 1;
      }
      this.showdailog();
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys(list);
        let a = this.$refs.tree.getHalfCheckedKeys();
        let b = this.$refs.tree.getCheckedKeys();
        list = b.concat(a);
        this.getselect(list);
      });
    },
    DelHandle(index) {
      this.carryMode.splice(index, 1);
    },
    getimgs(val) {
      this.forms.business_license = val;
    },
    getlist() {
      if (this.id == -1) {
        this.carryMode = [
          {
            district: "",
            first_piece: "",
            first_weight: "",
            first_amount: "",
            second_piece: "",
            second_weight: "",
            second_amount: "",
            district_value: "全国统一运费"
          }
        ];
        return false;
      }
      var data = {
        id: this.id
      };
      getfreightdetail(data).then(res => {
        var jsondata = res.msg;
        this.forms = objextend(this.forms, jsondata);
        this.carryMode =
          jsondata.carry_mode_type == 0
            ? jsondata.carryModeNum
            : jsondata.carryModeWeight;
        this.carryMode.forEach(a => {
          a.district = a.district.split(",");
        });
        this.no_carry = jsondata.no_carry.split(",");
        this.no_carry_value = jsondata.no_carry_value;
        this.forms.id = jsondata.id;
        this.forms.update_time = jsondata.update_time;
      });
    },
    getdata() {
      var data = this.forms;
      let list = [];
      if (data.carry_mode_type == 0) {
        this.carryMode.forEach(a => {
          let district = a.district ? a.district.join(",") : "";
          list.push({
            district: district,
            district_value: a.district_value,
            first_piece: a.first_piece,
            first_amount: a.first_amount,
            second_piece: a.second_piece,
            second_amount: a.second_amount
          });
        });
        data.carryModeNum = list;
      } else if (data.carry_mode_type == 1) {
        this.carryMode.forEach(a => {
          let district = a.district ? a.district.join(",") : "";
          list.push({
            district: district,
            district_value: a.district_value,
            first_weight: a.first_weight,
            first_amount: a.first_amount,
            second_weight: a.second_weight,
            second_amount: a.second_amount
          });
        });
        data.carryModeWeight = list;
      }
      data.no_carry = this.no_carry.join(",");
      data.no_carry_value = this.no_carry_value;
      return data;
    },
    addSave() {
      var _this = this;
      this.$refs.userForm.validate(valid => {
        if (valid) {
          let data = this.getdata();
          savefreight(data).then(res => {
            _this.close();
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    editSave() {
      var _this = this;
      this.$refs.userForm.validate(valid => {
        if (valid) {
          let data = this.getdata();

          editfreight(data).then(res => {
            _this.close();
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    close() {
      this.forms = {
        name: "",
        express_id: "",
        carry_mode_type: 0,
        is_default: 0,
        sort: 1,
        status: 1
      };
      // this.uid=''
      this.$emit("on-close");
    }
  },
  mounted() {
    console.log("es");

    if (this.id) {
      this.getlist();
    }
    this.getexpress();
  }
};
</script>

<style lang="scss" scoped>
/* .el-input {
  width: 270px;
} */
.form_input {
  width: 200px;
}
.carryMode_box {
  background-color: #f4f6f8;
  padding: 30px 20px;
  margin-top: 10px;
}
.box {
  width: 100%;
  /*padding: 60px;
    height: calc(100vh - 77px);
    overflow: scroll;*/
}
.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  height: 36px;
  .el-input {
    width: 160px;
  }
}
.panel-body {
  box-sizing: border-box;
  border: 1px solid #ededed;
  border-radius: 4px;
  height: 467px;
  width: 100%;
  overflow-y: auto;
  padding: 16px;
  padding-bottom: 0;
}
.panel-foot {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
